﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace iNet.Media.Imaging.Jpeg
{
	#region JpegSegment
	/// <summary>
	/// JPEG Segment。
	/// </summary>
	public struct JpegSegment
	{
		#region 欄位
		/// <summary>
		/// Segment 內容。
		/// </summary>
		public byte[] Contents;
		/// <summary>
		/// Segment 類型。
		/// </summary>
		public JpegSegmentType Type;
		#endregion
		#region 建構子
		/// <summary>
		/// 從指定的資料流初始化 JpegSegment 結構欄位。
		/// </summary>
		/// <param name="stream">提供資料的資料流。</param>
		public JpegSegment(Stream stream)
		{
			//確認
			if (stream == null)
				throw new ArgumentNullException("stream");

			//讀取
			byte[] buffer = new byte[2];
			if (stream.Read(buffer, 0, 2) < 2)
				throw new EndOfStreamException();

			//確認
			if (buffer[0] != 0xFF)
				throw new ArgumentException("");

			//設定欄位
			this.Type = (JpegSegmentType)buffer[1];

			//取得資料長度
			int length;
			if (this.Type == JpegSegmentType.SOI || this.Type == JpegSegmentType.EOI)
				length = 0;
			else
			{
				if (stream.Read(buffer, 0, 2) < 2)
					throw new EndOfStreamException();
				length = ((buffer[0] << 8) | buffer[1]) - 2;
			}

			//讀取資料
			this.Contents = new byte[length];
			if (length > 0)
			{
				if (stream.Read(this.Contents, 0, length) < length)
					throw new EndOfStreamException();
			}
		}
		#endregion
	}
	#endregion
	#region JpegSegmentType
	/// <summary>
	/// 表示 JPEG Segment 類型。
	/// </summary>
	public enum JpegSegmentType : byte
	{
		SOF0 = 0xC0,
		SOF1 = 0xC1,
		SOF2 = 0xC2,
		DHT = 0xC4,
		JPG = 0xC8,
		DAC = 0xCC,
		SOI = 0xD8,
		EOI = 0xD9,
		SOS = 0xDA,
		DQT = 0xDB,
		DNL = 0xDC,
		DRI = 0xDD,
		DHP = 0xDE,
		EXP = 0xDF,
		APP0 = 0xE0,
		APP1 = 0xE1,
		APP2 = 0xE2,
		APP15 = 0xEF,
		JPG0 = 0xF0,
		JPG13 = 0xFD,
		COM = 0xFE,
	}
	#endregion
}